package com.qk.aspect;

import com.qk.entity.OperateLog;
import com.qk.mapper.OperateLogMapper;
import com.qk.utils.CurrentUserHoler;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    //使用Around 实现
    @Around("@annotation(com.qk.anno.Log)")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        //1、创建对象
        OperateLog operateLog = new OperateLog();
        //2、为对象属性赋值
        //获取用户id
        operateLog.setOperateUserId(CurrentUserHoler.getCurrentUser());
        //获取操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        //获取类名
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        //获取方法名
        operateLog.setMethodName(pjp.getSignature().getName());
        //获取参数
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));
        //记录运行时间
        long begin = System.currentTimeMillis();
        //调用原始方法运行
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        operateLog.setCostTime(end - begin);

        operateLog.setReturnValue(result.toString());
        //保存日志到数据库
        operateLogMapper.insert(operateLog);
        //返回数据
        return result;

    }




}
